<template>
  <div>
    <Header :title="headerTitle"></Header>
    <div style="margin-top: 45px;">
      <!-- 购物车商品列表 -->
      <van-checkbox-group v-model="selectAll" ref="cartAllList" @change="allChange">
        <van-row v-for="(item,index) in cart" style="margin: 10px 0px;background-color: #FAFAFA;" :key="index">
          <!-- 复选框 -->
          <van-col span="2" style="display: flex;justify-content: center;margin-top: 10px;">
            <van-checkbox :name="index" />
            <!-- 根据下标计算价格 -->
          </van-col>

          <!-- 商品卡片 -->
          <van-col span="21">
            <van-card
              :price="item.goods.actualPrice"
              :title="item.goods.title"
              :thumb="item.goods.mainPic"
              @click-thumb="todetalis(item.goods.id)"
            >
              <template #num>
                <van-stepper v-model="item.num" integer @change="numChange" />
              </template>
            </van-card>
          </van-col>

          <!-- 删除按钮 -->
          <van-col span="1" style="display: flex;justify-content: center;margin-top: 10px;">
            <van-icon name="delete" color="red" @click="delGoods(index)" />
          </van-col>
        </van-row>
      </van-checkbox-group>

      <!-- 空状态 -->
      <van-empty
        class="custom-image"
        image="/image/shopping.png"
        description="登录后可同步购物车中商品"
        v-show="showEmpty"
      >
        <van-button round type="warning" @click="togoods">去购物</van-button>
      </van-empty>

      <!-- 底部提交订单区域 -->
      <van-submit-bar :price="total" button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="checked" @click="handleSelAll">全选</van-checkbox>
      </van-submit-bar>
    </div>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";
export default {
  components: {
    Header
  },
  data() {
    return {
      cart: [], //购物车的商品数组
      checked: false,
      total: 0, //总价，单位是分
      selectAll: [] //全部选中的商品
    };
  },
  computed: {
    headerTitle() {
      return `购物车(${this.cart.length})`;
    },
    showEmpty() {
      let isShow = this.cart.length > 0 ? false : true;
      return isShow;
    }
  },
  created() {
    //初始化购物车数据
    let cart = localStorage.cart;
    if (cart != undefined) {
      this.cart = JSON.parse(cart);
    }
  },
  methods: {
    onSubmit() {
      //提交订单
    },
    numChange() {
      //当商品数量修改时执行的方法
      //同步到localStorage
      localStorage.cart = JSON.stringify(this.cart);

      //计算总价
      if (this.selectAll.length > 0) {
        //判断当前是否有选中的商品
        this.zong(); // 调用计算总价的方法
      }
    },
    handleSelAll() {
      //全选
      if (this.checked) {
        this.selectAll = this.cart;
        this.$refs.cartAllList.toggleAll(this.checked);
      } else {
        this.selectAll = [];
      }
    },
    allChange(names) {
      //当复选框数组中的选中项发生变化时，就会执行该方法
      if (names.length < this.cart.length) {
        this.checked = false;
      } else if (names.length == this.cart.length) {
        this.checked = true;
      }
      this.zong(); //调用计算总价的方法
    },
    zong() {
      //计算商品总价
      this.total = 0; //清空历史记录
      //根据下标计算总价
      this.selectAll.map(i => {
        let cart = this.cart[i]; //获取购物车的商品对象
        let money = cart.num * cart.goods.actualPrice * 100; //单位分
        this.total += money;
      });
    },
    delGoods(index) {
      if (this.selectAll.includes(index)) {
        //被选中状态
        this.$notify({
          type: "danger",
          message: "删除商品前请先取消选中状态"
        });
      } else {
        this.$dialog
          .confirm({
            title: "删除提示",
            message: `你确定删除商品：
${this.cart[index].goods.title}
吗？`
          })
          .then(() => {
            //删除
            this.cart.splice(index, 1);
            localStorage.cart = JSON.stringify(this.cart); //同步
          })
          .catch(() => {
            console.log("no...");
          });
      }
    },
    togoods() {
      //去商品列表页
      this.$router.push({
        name: "goods"
      });
    },
    todetalis(id) {
      //路由跳转
      this.$router.push({
        path: "/details",
        query: {
          id
        }
      });
    }
  }
};
</script>

<style>
.custom-image .van-empty__image {
  width: 90px;
  height: 90px;
}
.bottom-button {
  width: 160px;
  height: 40px;
}
</style>
